﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Com.Stockstar.Quote.Model.Quote;
using SG.SDK.Configuration;
using SG.SDK;
using System.Configuration;

namespace Com.Stockstar.Quote.Common.Quote
{
    /// <summary>
    /// 行情代码表
    /// </summary>
    public class AllCodeSingleton
    {
        //获取代码表数据Thread
        private static Thread _codeThread = new Thread(new ParameterizedThreadStart(GetCodeData));
        //访问实例锁
        private static Object _instanceLockObject = new Object();
        //访问代码表锁
        private static Object _codeLockObject = new Object();
        //代码表
        private static List<SecurityCode> _codeList;
        //实例
        private static AllCodeSingleton _instance;
        //获取SG服务器地址
        private static string _sgSDKServerAddress = ConfigurationSettings.AppSettings["SGSDKServerAddress"];
        //获取G服务器端口
        private static int _sgSDKServerPort = Int32.Parse(ConfigurationSettings.AppSettings["SGSDKServerPort"]);
        //log4net日志
        protected static log4net.ILog _logger = log4net.LogManager.GetLogger("Quote");

        private AllCodeSingleton()
        {

        }

        #region 实例
        /// <summary>
        /// 实例
        /// </summary>
        public static AllCodeSingleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLockObject)
                    {
                        if (_instance == null)
                            _instance = CreateInstance();
                    }
                }

                return _instance;
            }
        }
        #endregion

        #region 创建实例
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <returns></returns>
        private static AllCodeSingleton CreateInstance()
        {
            return new AllCodeSingleton();
        }
        #endregion

        #region 启动
        /// <summary>
        /// 启动
        /// </summary>
        public static void Start()
        {
            _codeThread.Start();
        }
        #endregion

        #region 获取代码表数据
        /// <summary>
        /// 获取代码表数据
        /// </summary>
        /// <param name="obj"></param>
        private static void GetCodeData(object obj)
        {
            while (true)
            {
                DateTime currentTime = DateTime.Now;


                if (_codeList == null || _codeList.Count == 0)
                {
                    _codeList = GetCodeList();
                }
                else
                {
                    List<SecurityCode> newCodeList = GetCodeList();
                    if (newCodeList != null && newCodeList.Count > 0)
                    {
                        _codeList = newCodeList;
                    }
                }

                DateTime nextTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 9, 15, 0);
                int result = DateTime.Compare(currentTime, nextTime);
                if (result >= 0)
                    nextTime = nextTime.AddDays(1);

                double interval = (nextTime - currentTime).TotalMilliseconds;

                Thread.Sleep(TimeSpan.FromMilliseconds(interval));
            }
        }
        #endregion

        #region 获取代码表
        /// <summary>
        /// 获取代码表
        /// </summary>
        /// <returns></returns>
        private static List<SecurityCode> GetCodeList()
        {
            List<SecurityCode> dataList = new List<SecurityCode>();
            try
            {

                SDKClient client = new SDKClient(new ResourceAddress(_sgSDKServerAddress, _sgSDKServerPort), "SECURITY_CODE");
                client.SetIntFilterParams("MARKET", new int[] { 0, 1, 2 }); //0-未知, 1-上海，2-深圳, 
                //获取数据

                SGObject[] array = client.GetRows();
                if (array != null && array.Length > 0)
                {
                    foreach (SGObject data in array)
                    {
                        SecurityCode securityCode = new SecurityCode();
                        //证券代码
                        securityCode.Code = data["CODE"].ToString();
                        //证券简称
                        securityCode.Name = data["SHORT_NAME"].ToString();
                        //市场类型
                        securityCode.MarketType = data["MARKET"].NullIntValue();
                        //拼音缩写
                        securityCode.PinYin = data["PIN_YIN_ABB"].ToString();
                        //证券类型
                        securityCode.SecurtyType = data["TYPE"].NullIntValue();
                        //所属行业
                        securityCode.Industry = data["INDUSTRY"].ToString();
                        //行业代码
                        securityCode.IndustryCode = data["INDUSTRY_CODE"].ToString();
                        //概念板块
                        securityCode.ConceptPlate = data["CONCEPT"].ToString();
                        //概念板块代码
                        securityCode.ConceptPlateCode = data["CONCEPT_CODE"].NullIntValue();
                        //地域
                        securityCode.Region = data["REGION"].ToString();
                        //地域代码
                        securityCode.RegionCode = data["REGION_CODE"].NullIntValue();
                        //昨收
                        securityCode.PreClosePrice = data["PRE_CLOSE"].NullDoubuleValue();
                        //更新时间
                        securityCode.UpdateTime = data["UPDATE_TIME"].NullDateTimeValue();
                        //停牌状态
                        securityCode.HaltState = data["STOP_STATE"].NullIntValue();
                        //上市状态
                        securityCode.ListedState = data["LIST_STATUS"].NullIntValue();

                        dataList.Add(securityCode);
                    }
                }


                int count = dataList != null ? dataList.Count : 0;
                _logger.Info(String.Format("获取代码表成功！数据个数{0}", count));
            }

            catch (Exception ex)
            {
                _logger.Error("从SG.SDK接口获取代码表出错！", ex);
                return null;
            }

            return dataList;

        }
        #endregion

        #region 代码列表
        /// <summary>
        /// 代码列表
        /// </summary>
        public List<SecurityCode> CodeList
        {
            get
            {
                if (_codeList == null || _codeList.Count == 0)
                {
                    lock (_codeLockObject)
                    {
                        if (_codeList == null || _codeList.Count == 0)
                            _codeList = GetCodeList();
                    }
                }
                return _codeList;
            }
        }
        #endregion
    }

}
